package com.common.client;

import java.util.ArrayList;
import java.util.TreeMap;

import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.menu.Menu;
import com.smartgwt.client.widgets.menu.MenuItem;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripButton;

public class ToolbarAndMenu {

	private TreeMap<String, ToolbarAndMenuItems> treeMap;
	private TreeMap<String, ToolStripButton> toolBarButtons;
	private TreeMap<String, MenuItem> menuItems;
	private ToolStrip toolStrip;
	private Menu menu;

	public ToolbarAndMenu(ArrayList<ToolbarAndMenuItems> toolbarAndMenuItems) {

		treeMap = new TreeMap<String, ToolbarAndMenuItems>();
		toolBarButtons = new TreeMap<String, ToolStripButton>();
		menuItems = new TreeMap<String, MenuItem>();
		toolStrip = new ToolStrip();
		menu = new Menu();
		for (ToolbarAndMenuItems item : toolbarAndMenuItems) {
			treeMap.put(item.getName(), item);
			ToolStripButton button = new ToolStripButton(item.getCaption(),
					item.getImgUrl());
			MenuItem menuItem = new MenuItem(item.getCaption(),
					item.getImgUrl());
			if (item.isDisabled())
				button.disable();

			menuItem.setEnabled(!item.isDisabled());
			final String action = item.getName();
			final ToolbarAndMenuItems aitem = item;
			ClickHandler ch = new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					aitem.getOnEventHendler()
							.onLogOn(new ObjectOnEvent(action));
				}
			};
			button.addClickHandler(ch);
			menuItem.addClickHandler(new com.smartgwt.client.widgets.menu.events.ClickHandler() {
				@Override
				public void onClick(MenuItemClickEvent event) {
					aitem.getOnEventHendler()
							.onLogOn(new ObjectOnEvent(action));

				}
			});
			toolBarButtons.put(action, button);
			menuItems.put(action, menuItem);
			toolStrip.addButton(button);
			menu.addItem(menuItem);
		}

	}

	public void setItemEnable(String name, boolean enable) {
		ToolStripButton button = toolBarButtons.get(name);
		if (button != null) {
			if (enable)
				button.enable();
			else
				button.disable();
		}
		MenuItem menuItem = menuItems.get(name);
		if (menuItem != null)
			menuItem.setEnabled(enable);
	}

	public ToolStrip getToolStrip() {
		return toolStrip;
	}

	public Menu getMenu() {
		return menu;
	}

}
